package cn.cqone.crm.service.impl;

import cn.cqone.crm.domain.Permission;
import cn.cqone.crm.dto.IdsDto;
import cn.cqone.crm.mapper.PermissionMapper;
import cn.cqone.crm.query.PermissionQuery;
import cn.cqone.crm.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class PermissionServiceImpl extends BaseServiceImpl<Permission,Long,PermissionQuery> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    //根据用户id查询他拥有的权限
    @Override
    public List<Permission> findPermissionByEmployeeId(Long employeeId) {
        return permissionMapper.findPermissionByEmployeeId(employeeId);
    }

    @Override
    public List<Permission> findPermission() {
        //查询出所有的父权限
        List<Permission> fatherPermission = permissionMapper.findFatherPermission();
        fatherPermission.forEach(f->{
            //当前父权限的所有子权限
            List<Permission> childPermission = permissionMapper.findChildPermission(f.getId());
            //把子权限添加到父权限中
            f.setChild(childPermission);
        });

        return fatherPermission;
    }

    //根据角色id和权限id去掉当前角色的权限
    @Override
    public void deleteRolePermission(Long roleId, Long permissionId) {
        permissionMapper.deleteRolePermission(roleId,permissionId);
    }

    //根据用户id批量添加权限
    @Override
    public void addRolePermission(Long role_id, IdsDto dto) {
        //查询当前用户拥有的权限
        List<Long> l = permissionMapper.findPermissionIdByRoleId(role_id);
        List<Permission> fatherPermission = permissionMapper.findFatherPermission();
        List<Long> father_id=new ArrayList();
        fatherPermission.forEach(f->{
            father_id.add(f.getId());
        });
        Long[] ids = dto.getPermission_ids();
        List<Long> list = Arrays.asList(ids);
        //判断，是否取消了某些权限，如果取消了，则需要去除掉用户的该权限
        l.forEach(p->{
            if(!list.contains(p)){
                permissionMapper.deleteRolePermission(role_id,p);
            }
        });
        for(Long id:ids){
            //如果该权限id已存在就不添加，不存在就添加，后面的条件是循环判断，要添加的权限是否包含父类权限，包含就不添加父类权限
            if(!l.contains(id)&&!father_id.contains(id)) {
                permissionMapper.addRolePermission(role_id, id);
            }
        }
    }
}
